import 'dart:developer' as dev;

import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import '../errors/failures.dart';
import '../errors/exceptions.dart';

/// 所有服务的基础类
abstract class BaseService extends GetxService {
  /// 初始化服务 - 添加特定的初始化逻辑
  @override
  void onInit() {
    super.onInit();
  }

  /// 服务关闭时的清理 - 添加特定的清理逻辑
  @override
  void onClose() {
    super.onClose();
  }

  /// 打印调试日志
  void logDebug(String message) {
    dev.log(
      message,
      name: runtimeType.toString(),
      time: DateTime.now(),
    );
  }

  /// 打印信息日志
  void logInfo(String message) {
    dev.log(
      message,
      name: runtimeType.toString(),
      time: DateTime.now(),
    );
  }

  /// 打印警告日志
  void logWarning(String message) {
    dev.log(
      message,
      name: runtimeType.toString(),
      time: DateTime.now(),
      level: 900,
    );
  }

  /// 打印错误日志
  void logError(String message, [dynamic error, StackTrace? stackTrace]) {
    dev.log(
      message,
      error: error,
      stackTrace: stackTrace,
      name: runtimeType.toString(),
      time: DateTime.now(),
      level: 1000,
    );
  }

  /// 统一错误处理
  Future<T> handleError<T>(Future<T> Function() task) async {
    try {
      return await task();
    } on ServerException catch (e) {
      debugPrint('ServerException: $e');
      throw ServerFailure(e.message);
    } on CacheException catch (e) {
      debugPrint('CacheException: $e');
      throw CacheFailure(e.message);
    } on NetworkException catch (e) {
      debugPrint('NetworkException: $e');
      throw NetworkFailure(e.message);
    } on UnauthorizedException catch (e) {
      debugPrint('UnauthorizedException: $e');
      throw UnauthorizedFailure(e.message);
    } catch (e) {
      debugPrint('UnexpectedException: $e');
      throw UnexpectedFailure(e.toString());
    }
  }

  /// 获取本地化字符串
  String translate(String key) {
    return key.tr;
  }
} 